#import "DbObject.h"
#import "MyStoreParsedResult.h"

@implementation DbObject

- (id) init
{
	if (self = [super init])
	{
		[self createDatabaseIfNeeded];
	}
	return self;
}

- (void) dealloc
{
	[super dealloc];
}

// Check and copy database.
- (void) createDatabaseIfNeeded
{
	BOOL success;
	NSError *error;

	database_name = @"MyBarcode.db";

	NSArray *document_paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documents_dir = [document_paths objectAtIndex:0];
	database_path = [documents_dir stringByAppendingPathComponent:database_name];
	NSFileManager *file_manager = [NSFileManager defaultManager];
	success = [file_manager fileExistsAtPath:database_path];

	if (success) return;

	NSString *app_db_path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:database_name];
	success = [file_manager copyItemAtPath:app_db_path toPath:database_path error:&error];
	
	if (!success)
	{
		NSAssert1(0, @"Failed to copy the database. Error: %@.", [error localizedDescription]);
	}
}

- (NSMutableArray *) getItems
{
	NSMutableArray *results = [NSMutableArray array];

	if (sqlite3_open([database_path UTF8String], &db_obj) == SQLITE_OK)
	{
		NSString *sql_stmt = @"SELECT * FROM MyBarcode";
		
		if (sqlite3_prepare_v2(db_obj, [sql_stmt UTF8String], -1, &statement, NULL) == SQLITE_OK)
		{
			while (sqlite3_step(statement) == SQLITE_ROW)
			{
				NSString *s = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
				
				NSArray *keys = [NSArray arrayWithObjects:@"qid", @"time", @"barcode", nil];
				NSArray *values = [NSArray arrayWithObjects:
								   [NSNumber numberWithInt:sqlite3_column_int(statement, 0)],
								   [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)],
								   [[[MyStoreParsedResult alloc] initWithSrcString:s] autorelease],
								   nil
				];
				NSMutableDictionary *row= [NSMutableDictionary dictionaryWithObjects:values forKeys:keys];
				[results addObject:row];
			}
		}
		else
			NSAssert1(0, @"Error while creating statement. '%s'", sqlite3_errmsg(db_obj));

		sqlite3_reset(statement);
	}
	else
		NSAssert1(0, @"Failed to open database. '%s'.", sqlite3_errmsg(db_obj));

	sqlite3_close(db_obj);
	return results;
}

- (void) insertItem : (NSString *) barcode
{
	long int qid = 0;
	NSString *current_time;
	NSDateFormatter *date_formatter = [[NSDateFormatter alloc] init];
	[date_formatter setDateStyle:NSDateFormatterShortStyle];
	[date_formatter setTimeStyle:NSDateFormatterShortStyle];

	if (sqlite3_open([database_path UTF8String], &db_obj) == SQLITE_OK)
	{
		NSString *sql_stmt = @"INSERT INTO MyBarcode(qid, time, barcode) VALUES(?, ?, ?)";
		
		if (sqlite3_prepare_v2(db_obj, [sql_stmt UTF8String], -1, &statement, NULL) != SQLITE_OK)
			NSAssert1(0, @"Error while creating statement. '%s'", sqlite3_errmsg(db_obj));
		else
		{
			sqlite3_bind_int64(statement, 1, qid);

			current_time = [date_formatter stringFromDate:[NSDate date]];
			[date_formatter release];
			sqlite3_bind_text(statement, 2, [current_time UTF8String], -1, SQLITE_TRANSIENT);

			sqlite3_bind_text(statement, 3, [barcode UTF8String], -1, SQLITE_TRANSIENT);
		}
		
		if (sqlite3_step(statement) != SQLITE_DONE)
			 NSAssert1(0, @"Error while inserting data. '%s'.", sqlite3_errmsg(db_obj));

		sqlite3_reset(statement);
	}
	else
		NSAssert1(0, @"Failed to open database. '%s'.", sqlite3_errmsg(db_obj));

	
	sqlite3_close(db_obj);
	return;
}

- (void) deleteItem : (NSString *) barcode
{
	if (sqlite3_open([database_path UTF8String], &db_obj) == SQLITE_OK)
	{
		NSString *sql_stmt = @"DELETE FROM MyBarcode WHERE barcode = ?";

		if (sqlite3_prepare_v2(db_obj, [sql_stmt UTF8String], -1, &statement, NULL) != SQLITE_OK)
			NSAssert1(0, @"Error while creating statement. '%s'", sqlite3_errmsg(db_obj));
		else
			sqlite3_bind_text(statement, 1, [barcode UTF8String], -1, SQLITE_TRANSIENT);

		if (sqlite3_step(statement) != SQLITE_DONE)
			 NSAssert1(0, @"Error while inserting data. '%s'.", sqlite3_errmsg(db_obj));

		sqlite3_reset(statement);
	}
	else
		NSAssert1(0, @"Failed to open database. '%s'.", sqlite3_errmsg(db_obj));

	sqlite3_close(db_obj);
	return;
}

@end
